﻿#region

using System;
using System.Collections.Generic;
using System.Net;
using System.Xml;
using AmazonProductAdvtApi;

#endregion

namespace iTunesArtworkApp.Core
{
    /// <summary>
    ///   The artwork service is responsible for retrieving the album art.
    /// </summary>
    public class ArtworkService : IArtworkService
    {
        /// <summary>
        ///   The amazon web service domain.
        /// </summary>
        private const string DESTINATION = "ecs.amazonaws.com";

        /// <summary>
        ///   Application specific settings.
        /// </summary>
        private readonly ISettings _settings;

        #region  Constructor 

        /// <summary>
        ///   Initializes a new instance of the <see cref = "ArtworkService" /> class.
        /// </summary>
        /// <param name = "settings">The settings.</param>
        public ArtworkService(ISettings settings)
        {
            _settings = settings;

            if (string.IsNullOrEmpty(_settings.AwsAccessKeyId))
                throw new ArgumentException("AwsAccessKeyId is empty. Please check settings.");

            if (string.IsNullOrEmpty(_settings.AwsSecretKey))
                throw new ArgumentException("AwsSecretKey is empty. Please check settings.");

        }

        #endregion

        /// <summary>
        ///   Gets the album artwork for the specified album.
        /// </summary>
        /// <param name = "album">The album that requires artwork.</param>
        public void GetArtwork(ref Album album)
        {
            // preconditions
            if (album == null) throw new ArgumentNullException("album");
            if (string.IsNullOrEmpty(album.AlbumName))
                return;
            if (string.IsNullOrEmpty(album.Artist))
                return;

            // Build the Query Params for the REST Service
            var requestParameters = new Dictionary<string, string>();
            requestParameters["Service"] = "AWSECommerceService";
            requestParameters["Version"] = "2009-11-01";
            requestParameters["Operation"] = "ItemSearch";
            requestParameters["ContentType"] = "text/xml";
            requestParameters["ResponseGroup"] = "Images";
            requestParameters["SearchIndex"] = "Music";
            requestParameters["Artist"] = album.Artist;
            requestParameters["Keywords"] = album.AlbumName;

            // Build the REST Request URL and sign it according to Amazon's specification
            var helper = new SignedRequestHelper(_settings.AwsAccessKeyId, _settings.AwsSecretKey, DESTINATION);
            var requestUrl = helper.Sign(requestParameters);

            // Build the Amazon Url that has the album art image.
            album.Artwork.DownloadUrl = GetAlbumDownloadUrl(requestUrl);
        }

        #region  Private Methods 

        /// <summary>
        ///   Gets the album download URL.
        /// </summary>
        /// <param name = "url">The request url for the Amazon Product Service.</param>
        /// <returns>The download url for the album image</returns>
        private static string GetAlbumDownloadUrl(string url)
        {
            var request = WebRequest.Create(url);
            var response = request.GetResponse();

            var xmlDoc = new XmlDocument();
            xmlDoc.Load(response.GetResponseStream());
            var namespaceManager = new XmlNamespaceManager(xmlDoc.NameTable);
            namespaceManager.AddNamespace("def", "http://webservices.amazon.com/AWSECommerceService/2009-11-01");

            var nodes =
                xmlDoc.SelectNodes(
                    "/def:ItemSearchResponse/def:Items/def:Item[1]/def:ImageSets/def:ImageSet/def:LargeImage/def:URL",
                    namespaceManager);
            if (nodes == null || nodes.Count == 0)
                return string.Empty;

            return nodes[0].InnerText;
        }

        #endregion
    }

    // end class
}